package com.shop.cloud.common.exception;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.shop.cloud.common.mapper.JsonMapper;
import com.shop.cloud.util.ErrorCode;
import com.shop.cloud.util.Response;
import com.shop.cloud.util.ResponseUtil;

/**
 * 统一异常处理
 */
public class ExceptionResolver implements HandlerExceptionResolver {

	private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionResolver.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
		exception.printStackTrace();
		Response responseDataResponse = ResponseUtil.error();
		response.setContentType("application/json;charset=UTF-8");
		response.setStatus(HttpStatus.OK.value());
		 if(exception instanceof ServiceException){  
			 ServiceException serviceException= ((ServiceException)exception);
			 ErrorCode errorCode=serviceException.getErrorCode();
			 if(errorCode==null){
				 responseDataResponse=ResponseUtil.error(ErrorCode.PARAMETER_INVALID,serviceException.getMessage());
			 }else{
				 responseDataResponse=ResponseUtil.error(errorCode);
			 }
	     }
		 try {
	 			PrintWriter writer = response.getWriter();
	 			writer.write(JsonMapper.nonDefaultMapper().toJson(responseDataResponse));
	 			writer.flush();
	 			writer.close();
	 		} catch (IOException ie) {
	 			ie.printStackTrace();
	 			LOGGER.error("Failed to serialize the object to json for exception resolver!", ie);
	 		}
		return new ModelAndView();
	}
}
